#include<bits/stdc++.h>
using namespace std;

string s;
string ans="123804765";
vector<int> edges[9]={
	{1,3},{0,2,4},{1,5},
	{0,4,6},{1,3,5,7},{2,4,8},
	{3,7},{4,6,8},{5,7}
};


int main()
{
	cin>>s;
	if(s==ans) 
	{
		cout<<0;
		return 0;
	}
	
	queue<string> que1;
	queue<string> que2;
	unordered_map<string,bool> mp1;
	unordered_map<string,bool> mp2;
	
	que1.push(s);
	que2.push(ans);
	mp2[ans]=true;
	mp1[s]=true;
	int step1=0;
	int step2=0;

	while(true)
	{
		int size1=que1.size();
		step1++;
		mp1.clear();
		for(int i=0;i<size1;i++)
		{
			string s1=que1.front();
			que1.pop();
			int j;
			for(j=0;s1[j]!='0';j++){}
			for(auto u:edges[j])
			{
				string temp=s1;
				swap(temp[j],temp[u]);
				if(mp2[temp]==true)
				{
					cout<<step1+step2;
					return 0;
				}
				if(!mp1.count(temp))
				{
					mp1[temp]=true;
					que1.push(temp);
				}
			}
		}

		//
		int size2=que2.size();
		step2++;
		mp2.clear();
		for(int i=0;i<size2;i++)
		{
			string s1=que2.front();
			que2.pop();
			int j;
			for(j=0;s1[j]!='0';j++){}
			for(auto u:edges[j])
			{
				string temp=s1;
				swap(temp[j],temp[u]);
				if(mp1[temp]==true)
				{
					cout<<step1+step2;
					return 0;
				}
				if(!mp2.count(temp))
				{
					mp2[temp]=true;
					que2.push(temp);
				}
			}
		}
	}
	return 0;
}
